package utils

import (
	"errors"
	"io/ioutil"
	"log"
	"net/http"
)

// 分成两个请求函数方便理解过程

func SendForAccessToken(url string) (resp []byte, err error) {
	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		return
	}
	req.Header.Add("Content-Type", "application/json")

	client := &http.Client{}
	response, err := client.Do(req)
	if err != nil {
		return
	}
	defer response.Body.Close()

	if response.StatusCode != 200 {
		err = errors.New("http status err")
		log.Fatalln(err)
		return
	}

	resp, err = ioutil.ReadAll(response.Body)
	return
}

func SendForUserData(url, accessToken string) (resp []byte, err error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Authorization", "token "+accessToken)

	client := &http.Client{}
	response, err := client.Do(req)
	if err != nil {
		return
	}
	defer response.Body.Close()

	if response.StatusCode != 200 {
		err = errors.New("http status err")
		log.Fatalln(err)
		return
	}

	resp, err = ioutil.ReadAll(response.Body)
	return
}

